package com.party.admin.web.controller.city;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Sets;
import com.party.admin.utils.RealmUtils;
import com.party.admin.web.dto.AjaxResult;
import com.party.common.paging.Page;
import com.party.common.utils.LangUtils;
import com.party.core.model.BaseModel;
import com.party.core.model.city.City;
import com.party.core.model.mall.MallCategory;
import com.party.core.service.city.ICityService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

/**
 * 开放城市
 *
 * @author Administrator
 */
@Controller
@RequestMapping(value = "/city")
public class CityController {

    @Autowired
    private ICityService cityService;

    @RequestMapping(value = "list")
    public ModelAndView list(City city, Page page) {
        ModelAndView mv = new ModelAndView("city/cityList");
        page.setLimit(20);
        city.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
        List<City> list = cityService.listPage(city, page);
        mv.addObject("list", list);
        mv.addObject("city", city);
        mv.addObject("page", page);
        return mv;
    }

    @RequestMapping(value = "form")
    public ModelAndView form(String id, Page page) {
        ModelAndView mv = new ModelAndView("city/cityForm");
        City city = cityService.get(id);
        mv.addObject("city", city);
        return mv;
    }

    /**
     * 验证城市名称是否重复
     */
    @ResponseBody
    @RequestMapping(value = "validateName", method = RequestMethod.POST)
    public AjaxResult validateNameRepeate(City city) {
        AjaxResult ajaxResult = new AjaxResult();
        city.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
        List<City> list = cityService.validateName(city);
        if (null != list && list.size() > 0) {
            ajaxResult.setSuccess(false);
        } else {
            ajaxResult.setSuccess(true);
        }
        return ajaxResult;
    }

    /**
     * 保存城市
     */
    @ResponseBody
    @RequestMapping(value = "save")
    public AjaxResult save(City city, BindingResult result) throws Exception {
        AjaxResult ajaxResult = new AjaxResult();
        // 数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErros = result.getAllErrors();
            ajaxResult.setDescription(allErros.get(0).getDefaultMessage());
            return ajaxResult;
        }
        city.setUpdateDate(new Date());
        city.setUpdateBy(RealmUtils.getCurrentUser().getId());
        if (StringUtils.isNotEmpty(city.getId())) {// 编辑表单保存
            cityService.update(city);
        } else {
            cityService.insert(city);
        }
        cityService.updateCityRedis();
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }

    /**
     * 删除开放城市
     */
    @ResponseBody
    @RequestMapping(value = "del", method = RequestMethod.POST)
    public AjaxResult del(String id) throws Exception {
        AjaxResult ajaxResult = new AjaxResult();
        if (StringUtils.isNotBlank(id)) {
            cityService.deleteLogic(id);
            cityService.updateCityRedis();
        } else {
            ajaxResult.setSuccess(false);
            return ajaxResult;
        }
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }

    /**
     * 获取城市信息(用于筛选活动，商品列表)
     *
     * @return 行业信息列表
     */
    @RequestMapping("/cityInfo")
    public ModelAndView cityInfo(City city, String categoryIds, Page page) {
        page.setLimit(10);
        ModelAndView modelAndView = new ModelAndView("enterpriseservice/selectEpCategory");
        //获取已开放的
        city.setIsOpen(1);
        List<City> list = cityService.listPage(city, page);
        modelAndView.addObject("list", list);
        modelAndView.addObject("page", page);
        modelAndView.addObject("categoryIds", categoryIds);

        boolean isAllselect = false;

        Set<String> allCategoryIds = Sets.newHashSet();
        if (com.party.common.utils.StringUtils.isNotEmpty(categoryIds)) {
            allCategoryIds.addAll(Arrays.asList(categoryIds.split(",")));
        }
        if (allCategoryIds.size() > 0) {
            List<City> mallCategories = cityService.batchList(allCategoryIds, new City(), null);
            mallCategories = LangUtils.transform(mallCategories, input -> {
                City category = new City();
                category.setId(input.getId());
                category.setName(input.getName());
                return category;
            });

            isAllselect = mallCategories.containsAll(list);

            modelAndView.addObject("categoryJson", JSONObject.toJSONString(mallCategories));
        } else {
            modelAndView.addObject("categoryJson", JSONObject.toJSONString(new ArrayList<MallCategory>()));
        }
        modelAndView.addObject("isAllselect", isAllselect);
        return modelAndView;
    }
}
